<template>
    <div>
        <el-row>
            <el-col :span="24" v-show="isShow" style="margin-bottom: 10px;">
                <el-space :size="2" wrap>
                    <el-input v-model="search" placeholder="搜索" style="max-width: 300px;" clearable />
                    <el-button :icon="Search" plain>搜索</el-button>
                </el-space>
            </el-col>
            <el-col style="display: flex;justify-content: space-between; margin-bottom: 10px;">
                <el-button type="primary" @click="addRoutes" :icon="Plus" plain>新 增 路 由</el-button>
                <el-space warp>
                    <el-button :icon="Search" @click="SearchTable" plain round />
                    <el-button :icon="Refresh" @click="RefreshTable" plain round />
                </el-space>
            </el-col>
            <el-col :span="24">
                <el-table :data="TableData" size="small" row-key="id" :tree-props="{ children: 'children' }" v-loading="loading"
                    :header-cell-style="{ background: '#f4f6f8', width: '95%' }">
                    <el-table-column prop="title" label="标题名" width="200" :header-cell-class-name="'custom-header'" />
                    <el-table-column label="图标" width="60" align="center" :header-cell-class-name="'custom-header'">
                        <template #default="{ row }">
                            <SvgIcon :name="row.icon ? row.icon : ''" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="path" label="路由地址" width="180" :header-cell-class-name="'custom-header'" />
                    <el-table-column prop="name" label="路由名" width="150" :header-cell-class-name="'custom-header'" />
                    <el-table-column prop="component" label="组件名" width="180" :header-cell-class-name="'custom-header'" />
                    <el-table-column prop="redirect" label="重定向" :header-cell-class-name="'custom-header'" />
                    <el-table-column prop="create" label="创建日期" :header-cell-class-name="'custom-header'" />
                    <el-table-column prop="permission" label="权限" width="110" align="center"
                        :header-cell-class-name="'custom-header'">
                        <template #default="{ row }">
                            <el-tag v-if="row.permission === 'SuperAdmin'" disable-transitions>超级管理员</el-tag>
                            <el-tag v-else-if="row.permission === 'Admin'" disable-transitions>管理员</el-tag>
                            <el-tag v-else disable-transitions>普通用户</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="状态" width="70" :header-cell-class-name="'custom-header'">
                        <template #default="{ row }">
                            <el-tag :type="row.isMenu === 0 ? 'success' : 'danger'">
                                {{ row.isMenu === 0 ? '正常' : '禁用' }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="路由控制" width="250" :col="3" align='center' fixed="right"
                        :header-cell-class-name="'custom-header'">
                        <template #default="{ row }">
                            <el-space :size="10" warp>
                                <el-switch v-model="row.isMenu" :loading="loadingSwitch[row.id]"
                                    :before-change="() => beforeChange(row)" inline-prompt active-text="开" inactive-text="关"
                                    :active-value="0" :inactive-value="1" />
                                <el-button type="warning" @click="dialog(row)" :icon="Edit" link>修 改</el-button>
                                <el-button type="danger" @click="DeleteHandler(row)" :icon="Delete" link>删 除</el-button>
                            </el-space>
                        </template>
                    </el-table-column>
                    <template #empty>
                        <el-empty description="暂无数据" />
                    </template>
                </el-table>
            </el-col>
        </el-row>
        <el-dialog v-model="dialogFormVisible" width="30%" title="修改路由配置">
            <el-form :model="selectedRow" :rules="rules" label-width="80" ref="changeRoutesRuleRef" status-icon>
                <el-form-item label="路由地址" prop="path">
                    <el-input v-model="selectedRow.path" autocomplete="off" clearable />
                </el-form-item>
                <el-form-item label="路由名" prop="name">
                    <el-input v-model="selectedRow.name" autocomplete="off" clearable />
                </el-form-item>
                <el-form-item label="图标名" prop="icon">
                    <el-input v-model="selectedRow.icon" autocomplete="off" clearable />
                </el-form-item>
                <el-form-item label="标题名" prop="title">
                    <el-input v-model="selectedRow.title" autocomplete="off" clearable />
                </el-form-item>
            </el-form>
            <span class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="ChangeHandler(changeRoutesRuleRef)">
                    修改
                </el-button>
            </span>
        </el-dialog>
        <el-dialog v-model="addRoutesDialog" width="30%" title="新增路由">
            <el-form :model="form" :rules="rules" ref="addRoutesRuleRef" label-width="80" status-icon>
                <el-form-item label="路由地址" prop="path">
                    <el-input v-model="form.path" autocomplete="off" clearable />
                </el-form-item>
                <el-form-item label="路由名" prop="name">
                    <el-input v-model="form.name" autocomplete="off" clearable />
                </el-form-item>
                <el-form-item label="组件名" prop="component">
                    <el-input v-model="form.component" autocomplete="off" clearable />
                </el-form-item>
                <el-form-item label="路由跳转" prop="redirect">
                    <el-input v-model="form.redirect" autocomplete="off" clearable />
                </el-form-item>
                <el-form-item label="角色" prop="roles">
                    <el-checkbox-group v-model="form.roles">
                        <el-checkbox label="User" name="roles">用户</el-checkbox>
                        <el-checkbox label="Admin" name="roles">管理员</el-checkbox>
                        <el-checkbox label="SuperAdmin" name="roles">超级管理员</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
                <el-form-item label="图标名" prop="icon">
                    <el-input v-model="form.icon" autocomplete="off" clearable />
                </el-form-item>
                <el-form-item label="标题名" prop="title">
                    <el-input v-model="form.title" autocomplete="off" clearable />
                </el-form-item>
                <el-form-item label="父路由" prop="parentId">
                    <el-cascader v-model="form.parentId" placeholder="选择" :options="options" :props="props" clearable />
                </el-form-item>
                <el-form-item label="权限" prop="permission">
                    <el-select v-model="form.permission" placeholder="选择" clearable>
                        <el-option label="普通用户" value="User" />
                        <el-option label="管理员" value="Admin" />
                        <el-option label="超级管理员" value="SuperAdmin" />
                    </el-select>
                </el-form-item>
                <span class="dialog-footer">
                    <el-button @click="resetForm(addRoutesRuleRef)">取 消</el-button>
                    <el-button type="primary" @click="submitForm(addRoutesRuleRef)">
                        添 加
                    </el-button>
                </span>
            </el-form>
        </el-dialog>
    </div>
</template>

<script setup>
import { computed, ref, onMounted, reactive } from 'vue';
import { Info, Add, Del, isMenu, Change } from "@/Apis/modules/pagesMg"
import { routes_pathRule, routes_nameRule, routes_titleRule } from '@/utils/validate'
import { ElSpace, ElRow, ElCol, ElIcon, ElMessage, ElMessageBox, ElButton, ElTable, ElTableColumn, ElEmpty, ElFormItem, ElForm, ElOption, ElSelect, ElDialog, ElInput, ElCascader, ElCheckboxGroup, ElCheckbox, ElSwitch, ElTag } from 'element-plus';
import { Refresh, Edit, Delete, Plus, Search } from '@element-plus/icons-vue'
import PagesMgStore from '@/stores/modules/PagesMgStore'

const loading = ref(false)
const store = PagesMgStore();
// 动态渲染页面并筛选
const TableData = computed(() => store.info);

// 异步获取数据
const GetRoutesInfo = async () => {
    loading.value = true;
    setTimeout(async () => {
        await Info();
        loading.value = false;
    }, 1000)
}

// 获取数据
onMounted(async () => {
    await GetRoutesInfo();
})

// 搜索
const isShow = ref(false);
const search = ref('');
const SearchTable = () => {
    return isShow.value = !isShow.value;
}

// 刷新
const RefreshTable = async () => {
    await GetRoutesInfo();
}

// 级联选择器
const props = {
    expandTrigger: 'hover',
    checkStrictly: true,
}

const flattenTree = (data) => {
    return data.reduce((acc, el) => {
        const flattenedItem = {
            value: el.id,
            label: el.title
        };

        if (el.children && el.children.length > 0) {
            flattenedItem.children = flattenTree(el.children);
        }

        acc.push(flattenedItem);
        return acc;
    }, []);
};

const options = computed(() => [
    {
        value: 0,
        label: '无',
    },
    ...flattenTree(store.info),
]);

// 验证规则
const rules = ref({
    path: [{ required: true, validator: routes_pathRule, trigger: 'blur' }],
    name: [{ required: true, validator: routes_nameRule, trigger: 'blur' }],
    roles: [{ required: true, trigger: 'blur' }],
    title: [{ required: true, validator: routes_titleRule, trigger: 'blur' }]
})

// 控制路由
const loadingSwitch = reactive({});
const beforeChange = (row) => {
    const data = {
        isMenu: row.isMenu === 0 ? 1 : 0,
        id: row.id
    }
    loadingSwitch[row.id] = true;
    return new Promise(async (resolve) => {
        await isMenu(data).then(() => {
            setTimeout(async () => {
                loadingSwitch[row.id] = false
                return resolve(true);
            }, 1000)
        }).catch((error) => {
            loadingSwitch[row.id] = false;
            ElMessage.error('切换失败');
        })
    })
}

// 对话框控制
const dialogFormVisible = ref(false)
const dialog = (row) => {
    // 使用展开运算符来创建一个新的对象，避免直接修改原始数据
    selectedRow.value = { ...row };
    dialogFormVisible.value = true;
}

// 修改动态路由
const changeRoutesRuleRef = ref();
const selectedRow = ref({
    path: null,
    name: null,
    icon: null,
    title: null,
});
const ChangeHandler = async (formEl) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            const { id, path, name, icon, title } = selectedRow.value;
            const data = { id, path, name, icon, title };

            await Change(data);
            dialogFormVisible.value = false
            await GetRoutesInfo();
        } else {
            ElMessage.error('验证未通过!')
        }
    })
}

// 删除动态路由
const DeleteHandler = (row) => {
    const data = row.id;
    ElMessageBox.confirm(
        '是否删除该路由?',
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            // 发起删除请求
            Del(data).then(() => {
                // 删除成功后更新前端页面上的数据
                const index = store.info.findIndex(item => item.id === data);
                if (index !== -1) {
                    store.info.splice(index, 1); // 从 store 中移除对应的行数据
                }
            });
        })
        .catch(() => {
            return
        })
}

// 重置表单
const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
    addRoutesDialog.value = false
}

// 打开对话框
const addRoutesDialog = ref(false)
const addRoutes = () => {
    addRoutesDialog.value = true;
}

// 新增路由
const addRoutesRuleRef = ref();
const form = ref({
    path: '/',
    name: '',
    component: null,
    redirect: null,
    roles: [],
    icon: null,
    title: '',
    parentId: null,
    permission: ''
})

const submitForm = async (formEl) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            const { roles, parentId, ...rest } = form.value;

            const data = {
                meta: JSON.stringify({ roles, title: form.value.title }),
                parentId: parentId[0],
                ...rest
            };

            await Add(data);
            await GetRoutesInfo();
            addRoutesDialog.value = false;
        } else {
            ElMessage.error('验证未通过!')
            addRoutesDialog.value = false;
        }
    })
}
</script>

<style scoped>
.dialog-footer {
    display: flex;
    justify-content: right;
}
</style>